#!/usr/bin/perl

# Usage: update.pl <db_postfix> <dbpass> <update_script>

use DBI;

my $updateScript;

open UPD, $ARGV[2];
while (<UPD>) { $updateScript .= $_;}
close UPD;

my %updateScripts;

# my $maxVersion = 0;
while ($updateScript =~ /\[\[(\d+)\]\](.*?)(?=\[\[|$)/gs)
{
    my $curScript  = $2;
    my $curVersion = $1;
    my @curScriptVector;
    
    while ($curScript =~ /([^;]+(?=;))/gs)
    {
        push @curScriptVector, $1;
    }
    
    $updateScripts{$curVersion} = \@curScriptVector;
}

my $dbName = "parshin_" . $ARGV[0];
my $pass = $ARGV[1];
my $dbh = DBI->connect("DBI:mysql:$dbName:localhost", $dbName, $pass) or die $DBI::errstr;

$dbh->do("SET NAMES utf8");

while(1)
{
    my @curVersionArray = $dbh->selectrow_array('select version from metadata');
    my $curVersion = $curVersionArray[0];
    
    last unless exists $updateScripts{$curVersion};
    
    print "Updating version $curVersion...\n";
    
    for (@{$updateScripts{$curVersion}})
    {
        print "Executing: $_\n";
        $dbh->do($_) or die $DBI::errstr 
    }
}

$dbh->disconnect();